import { useRef, useMemo, useState } from "react";
import eventExtension from '@/pages/utils/eventExtension'
import { useVisionStore, useForceUpdate } from '@/pages/index'
import { useCalculation } from './useCalculation';
import { useStyle } from './useInteractiveStyle';

const DynamicDropCode = 'DynamicDrop'

export default function DynamicDrop(props: any) {
  const store = useVisionStore()
  const { event } = store
  const currentNode = useRef(null)
  const eP = useRef(null)
  const flag = useRef(true)
  const { mouPosDataP } = useCalculation(currentNode, eP, store);
  const ItStyle = useStyle(
    mouPosDataP,
    currentNode?.current,
    5
  );
  const dropColorStyle = {
    borderColor: '#0840f8',
  };
  const forceUpdate = useForceUpdate()
  useMemo(() => {
    event.addQueue('mousemove', {
      code: DynamicDropCode,
      callBack: (e: any) => {
        console.log('yidong')
        flag.current = false
        eP.current = e;
        const dynamicMoveNode = store.moveOpNode;
        const _currentNode = eventExtension.getCurrentNodeByEvent(
          e,
          0,
          (node: any) => {
            // 需要满足目标节点的dropReceive，（在dropReceive中出现）
            const dragNode = dynamicMoveNode;
            console.log(dragNode)
            const dropNode = node;
            const _dragTag = dragNode.code
            const _dropReceive:any[] = dropNode.dataProps?.receipt || []
            return _dropReceive.includes(_dragTag)
          },
          store
        );
        currentNode.current = _currentNode
        forceUpdate()
      },
    });
    event.addQueue('mouseup', {
      code: DynamicDropCode,
      callBack: () => {
        if(currentNode.current && !flag.current) {
          console.log('放开', currentNode.current)
          const mouPosData:any = (mouPosDataP.current! as any).res;
          console.log(mouPosData)
          if(mouPosData[2]==="inside") {
            // console.log(currentNode.current)
            let parentNode:any = currentNode.current
            console.log(parentNode)
            parentNode.setChildren(store.moveOpNode)
            store.moveOpNode.setParent(parentNode)
            parentNode.forceUpdate()
          }
        }
        currentNode.current = null
        forceUpdate()
      }
    });
  }, []);

  return (
    <div
      className="dynamicDrop"
      style={eventExtension.modifyStyleTsForm(ItStyle.dynamicDrop)}
      hidden={!currentNode.current}
    >
      <span
        style={{ ...ItStyle.topSizeStyle, ...dropColorStyle }}
        className="top"
      />
      <span
        style={{ ...ItStyle.rightSizeStyle, ...dropColorStyle }}
        className="right"
      />
      <span
        style={{ ...ItStyle.bottomSizeStyle, ...dropColorStyle }}
        className="bottom"
      />
      <span
        style={{ ...ItStyle.leftSizeStyle, ...dropColorStyle }}
        className="left"
      />
    </div>
  );
}